package com.lq.controller;

import com.lq.pojo.Link;
import com.lq.pojo.User;
import com.lq.service.LinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LinkController {

    @Autowired
    private LinkService linkService;

    @RequestMapping("/deleteLink")
    public String deleteLink(String lId, Model model) {

        int linkId = Integer.parseInt(lId);

        linkService.deleteLinkByLinkId(linkId);

        return "forward:/getLink";
    }

    @RequestMapping("/getLink")
    public String getLink(HttpSession session, Model model) {

        User user = (User) session.getAttribute("user");
        List<Link> linkList = linkService.getAllLinks(user.getUserId());

        model.addAttribute("linkList", linkList);

        return "link";
    }

    @RequestMapping("/saveLink")
    public String saveLink(HttpServletRequest req) {

        User user = (User) req.getSession().getAttribute("user");
        Link link = new Link(
                req.getParameter("linkName"),
                req.getParameter("linkAddress")
        );

        if (linkService.saveLink(link, user.getUserId())) {

            return "forward:/getLink";
        }

        return null;
    }
}
